package controller.impl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import action.DataProcessAction;
import pojo.Command;
import processor.CommandProcessable;
import processor.DataProcessor;
import processor.impl.CommandProcessableImpl;
import controller.ServerController;

/**
 * 服务端Controller实现类
 * 
 * @author WUJA13
 * 
 */
public class ServerControllerImpl implements ServerController {

	// /命令解析处理类
	private CommandProcessable commandProcessable;
	// /数据处理类
	private DataProcessAction dataProcessAction;

	public ServerControllerImpl() {
		this.commandProcessable = new CommandProcessableImpl();
		this.dataProcessAction = new DataProcessAction();
		try {
			this.dataProcessAction.action();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void dealWithClient(InputStream in, OutputStream out)
			throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(in,
				"utf-8"));
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out,
				"utf-8"));
		writer.write("Please input command --->  ");
		writer.flush();
		String clientSaid;
		while ((clientSaid = reader.readLine()) != null) {
			// /每次收到 客户端的命令

			// // 首先，命令解析器 解析命令
			Command command = this.commandProcessable
					.dealWithCommand(clientSaid);

			// / 然后， 数据处理器 读取命令内容，并将 对应的响应 构造出来
			if (command != null) {
				StringBuilder sb = this.dataProcessAction
						.createServerAnswer(command);
				if (sb != null) {
					if (writer != null)
						writer.write(sb.toString());// /最终将信息响应给客户端
				}
			}
			if (writer != null) {
				writer.write("/t/nPlease input command --->  ");
				writer.flush();
			}
		}

		in.close();
		out.close();
	}

}
